﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace Wikey.Domain.Components
{
    public class SecondConfiguration
    {

        private ISessionFactory m_Factory;
        private string m_SchemaPath;

        public SecondConfiguration Configure()
        {

            m_SchemaPath = ConfigurationManager.AppSettings["NStackExample.Data.Configuration.SchemaPath"];

            m_Factory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2005
                        .ConnectionString(
                         x => x.FromConnectionStringWithKey("NStackExample.Data.Configuration.Db")))
                .Mappings(x => x.FluentMappings.AddFromAssemblyOf<TableNameConvention>()
                                .ExportTo(m_SchemaPath))
                .ExposeConfiguration(BuildSchema)
                .BuildSessionFactory();

            return this;
        }

        private void BuildSchema(NHibernate.Cfg.Configuration cfg)
        {
            SchemaExport SchemaExporter = new SchemaExport(cfg);
            SchemaExporter.SetOutputFile(Path.Combine(m_SchemaPath, "schema.sql"));
            SchemaExporter.Create(true, false);
        }

        public ISession OpenSession()
        {
            if (m_Factory == null) Configure();
            return m_Factory.OpenSession();
        }

    }

}
